﻿using MayEditor.App_Code;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.SignalR;
using Newtonsoft.Json;
using OpenAI_API;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using static MayEditor.Startup;

namespace MayEditor.Controllers
{
    public class ChatHub : Hub
    {
        public async Task SendMessage(string prompt, string chatId)
        {
            await Groups.AddToGroupAsync(Context.ConnectionId, chatId);
            string apiKey = AppSetting.GetAppSetting("APIkey");
            string answer = string.Empty;
            var api = new OpenAIAPI(apiKey);
            var chat = api.Chat.CreateConversation();
            api.ApiUrlFormat = AppSetting.GetAppSetting("OpenAIUrl");
            chat.Model = AppSetting.GetAppSetting("ChatModel");
            chat.AppendUserInput(prompt);
            string responsea = "";
            HubRes hubRes = new HubRes();
            hubRes.chatId = chatId;
            await foreach (var res in chat.StreamResponseEnumerableFromChatbotAsync())
            {
                responsea += res;
                hubRes.msg = responsea;
                await Clients.Group(chatId).SendAsync("ReceiveMessage", JsonConvert.SerializeObject(hubRes));
            }
            hubRes.isfinish = true;
            await Clients.Group(chatId).SendAsync("ReceiveMessage", JsonConvert.SerializeObject(hubRes));
        }
    }
}
